<?php
// +----------------------------------------------------------------------
// | ThinkPHP [ WE CAN DO IT JUST THINK ]
// +----------------------------------------------------------------------
// | Copyright (c) 2006-2016 http://thinkphp.cn All rights reserved.
// +----------------------------------------------------------------------
// | Licensed ( http://www.apache.org/licenses/LICENSE-2.0 )
// +----------------------------------------------------------------------
// | Author: 流年 <liu21st@gmail.com>
// +----------------------------------------------------------------------

// 应用公共文件
/**
 * 获取无限极分类
 * @param $data
 * @param string $key 主键
 * @param string $pKey 父键
 * @param string $childKey
 * @return array
 */
function getTreeList($data, $key = 'id', $pKey = 'pid', $childKey = 'children')
{
    if (empty($data)) {
        return [];
    }
    $tree = []; //返还的最终数组
    $newData = []; //

    foreach ($data as $datum) {
        //先将所有的评论回复的id取出来作为索引也就是新数组newdata的下标
        $newData[$datum[$key]] = $datum;
    }
    //循环新数组newdata
    foreach ($newData as $index => $value) {
        if ($value[$pKey] != 0) {
            //如果root_id大于0，代表是回复，将地址给到root_id的索引的child数组下(就给到这条回复的母评论下)
            $newData[$value[$pKey]][$childKey][] = &$newData[$index];
        } else {
            //为评论，将其按照id存入结果树种
            $tree[] = &$newData[$index];
        }
    }
    return $tree;
}
function getSubs($list, $id, $idname = 'id', $pidname = 'pid')
{
    $subs = array();
    foreach ($list as $item) {
        if ($item[$pidname] == $id) {
            $subs[] = $item[$idname];
            $subs = array_merge($subs, getSubs($list, $item[$id]));
        }
    }
    return $subs;
}
/**
 * 对象 转 数组
 *
 * @param object $obj 对象
 * @return array
 */
function object_to_array($obj)
{
    $obj = (array)$obj;
    foreach ($obj as $k => $v) {
        if (gettype($v) == 'resource') {
            return;
        }
        if (gettype($v) == 'object' || gettype($v) == 'array') {
            $obj[$k] = (array)object_to_array($v);
        }
    }
    return $obj;
}
/**
 * 数组 转 对象
 *
 * @param array $arr 数组
 * @return object
 */
function array_to_object($arr)
{
    if (gettype($arr) != 'array') {
        return;
    }
    foreach ($arr as $k => $v) {
        if (gettype($v) == 'array' || getType($v) == 'object') {
            $arr[$k] = (object)array_to_object($v);
        }
    }
    return (object)$arr;
}
/**
 * 密码加密
 */
function encrypwd($pwd, $salt)
{
    $str = MD5(MD5($pwd) . $salt);
    return $str;
}
/**
 * token名加密
 */
function encrytoken($id)
{
    return MD5($id . '_meteor');
}
/**
 * 密码验证
 */
function checkPwd($pwd)
{ // 正则表达式6-16位字符（英文/数字/!@#$%&~）三种组合
    $res = preg_match('/(?=.*[0-9])(?=.*[a-z])(?=.*[!@#$%&~]).{6,16}/', $pwd);
    return $res ? true : false;
}
/**
 * 手机号验证
 */
function checkPhone($pwd)
{ // 
    $res = preg_match('/^1[3-9]{1}[0-9]{9}$/', $pwd);
    return $res ? true : false;
}
